
import re
from . models import User
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q


# 通过账户获取用户的方法
# def get_user_by_account(account):
#
#     try:
#         if re.match(r'^1[3-9]\d{9}$', account):
#             user = User.objects.get(mobile=account)
#         else:
#             user = User.objects.get(username=account)
#     except User.DoesNotExist:
#         return None
#     else:
#         return user

#自己重写登录时的用户认证后端,
class UsernameMobileAuthBackend(ModelBackend):
    # 重写该方法，实现根据username过滤，或根据mobile过滤用户对象
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 查找用户
        try:
            # user = get_user_by_account(username)
            user = User.objects.get(Q(username=username) | Q(mobile=username))

        except User.DoesNotExist as e:
            return None
        # if user and user.check_password(password):
        #     return user
        


        # TODO: 如果当前登录验证是后台管理站点登录，必须是is_staff=True用户
        if request is None:
            # 是后台管理站点
            if not user.is_staff:
                return None # 用户身份认证失败



        # 校验密码
        if not user.check_password(password):
            return None

        return user


# 导入:
from django.conf import settings

from meiduo_mall.utils.secret import SecretOauth


# 2.生成激活链接
def generate_verify_email_url(request):
    # 1.user_id email
    data_dict = {
        'user_id': request.user.id,
        'email': request.user.email
    }
    # 2.将参数加密
    dumps_data = SecretOauth().dumps(data_dict)

    # 3.拼接 完整的激活路由
    verify_url = settings.EMAIL_VERIFY_URL + dumps_data

    return verify_url